import {
    Image,
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    ScrollView,
    Modal,
    Animated,
    useWindowDimensions, ImageBackground
} from 'react-native';
import {Stack, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import { Ionicons } from '@expo/vector-icons';
import {useEffect, useState} from "react";
import {SceneMap, TabView} from "react-native-tab-view";
import * as React from "react";
import Empty from "@/components/empty";

import cardImg from "@/assets/images/money/yu_liang_img.png"
import yuEImg from "@/assets/images/money/yu_e_img.png"
import {getGrainInfoDetail} from "@/store/slices/loginSlice";
import {useDispatch, useSelector} from "react-redux";
import {AppDispatch, RootState} from "@/store";
import { getMoneyquery } from "@/services/money"
import {loadingService} from "@/utils/loadingServer";


const experienceRoute = () => {
    const router = useRouter();
    const dispatch = useDispatch<AppDispatch>();

    const login = useSelector((state: RootState) => state.login);

    useEffect(() => {
        dispatch(getGrainInfoDetail());
    },[])

    const goExchange = function () {
        router.push("/money/exchange")
    };

    return (
      <ScrollView>
          <View style={styles.experienceContainer}>
              <ImageBackground source={cardImg}>
                  <View style={styles.experienceHeaderCard}>
                      <View style={styles.moneyCard}>
                          <Text style={styles.moneyCardText}>{ login?.gainInfo?.balance || 0 }</Text>
                      </View>
                      <TouchableOpacity onPress={goExchange}>
                          <View style={styles.exchangeBtn}>
                              <Text style={styles.exchangeBtnText}>
                                  兑换
                              </Text>
                          </View>
                      </TouchableOpacity>
                  </View>
              </ImageBackground>
              <View style={[styles.experienceListContainer]}>
                  {
                      login?.gainInfo.changeDetails?.length > 0 && login?.gainInfo?.changeDetails?.map((item: any, index: number) => {
                          return (
                              <View style={[styles.experienceContent]} key={index}>
                                  <View style={styles.experienceTitleWrap}>
                                      <View>
                                          <Text style={styles.experienceTitles}>{ item.actionName }</Text>
                                      </View>
                                      <View>
                                          <Text style={styles.experienceNumber}>+{ item.amount }</Text>
                                      </View>
                                  </View>
                                  <View style={styles.experienceDate}>
                                      <Text style={styles.experienceDateText}>{ item?.changeTime }</Text>
                                  </View>
                              </View>
                          )
                      })
                  }
              </View>
          </View>
      </ScrollView>
    );
};

const moneyRoute = () => {

    const [moneyData, setMoneyData] = useState({});

    useEffect(() => {
        loadingService.show();
        getMoneyquery()
            .then(res => {
                setMoneyData(res.data);
                loadingService.hide();
            })
            .catch(err => {
                console.log('err', err);
                loadingService.hide();
            })
    }, [])

    return (
       <ScrollView>
           <View style={styles.moneyContainer}>
               <View style={styles.moneyYueCard}>
                   <ImageBackground source={yuEImg} >
                       <View style={styles.moneyYueMoneyWarp}>
                           <View style={styles.moneyYueMoneyWarpTitle}>
                               <Text style={styles.moneyYueMoneyWarpTitleText}>当前余额(元)</Text>
                           </View>
                           <View style={styles.moneyYueMoneyWarpTitleNumber}>
                               <Text style={styles.moneyYueMoneyWarpTitleNumberText}>{ moneyData.balance }</Text>
                           </View>
                       </View>
                       <View style={styles.submitWarp}>
                           <TouchableOpacity>
                               <View style={styles.reqMoney}>
                                   <Text style={styles.reqMoneyText}>发起提现</Text>
                               </View>
                           </TouchableOpacity>
                           <TouchableOpacity>
                               <View style={styles.reqMoneyHistory}>
                                   <Text style={styles.reqMoneyHistoryText}>提现记录</Text>
                               </View>
                           </TouchableOpacity>
                       </View>
                   </ImageBackground>
               </View>
               <View style={styles.billContainer}>
                   <View style={styles.billList}>
                      <View>
                          <Text>待提现</Text>
                      </View>
                       <View>
                           <Text style={styles.billMoney}>¥{ moneyData?.pendingWithdrawal }</Text>
                       </View>
                   </View>
                   <View style={styles.billList}>
                       <View>
                           <Text>已提现</Text>
                       </View>
                       <View>
                           <Text style={styles.billMoney}>¥{ moneyData?.withdrawn }</Text>
                       </View>
                   </View>
                   <View style={[styles.billList, styles.noBottom]}>
                       <View>
                           <Text>待入账</Text>
                       </View>
                       <View>
                           <Text style={styles.billMoney}>¥{ moneyData?.toBeCredit }</Text>
                       </View>
                   </View>
               </View>
           </View>
       </ScrollView>
    );
};

const cardRoute = () => {

    return (
        <Empty title={'敬请期待~'} />
    );
};


// 自定义的 TabBar 组件
const CustomTabBar = ({ navigationState, position, setIndex }) => {
    // 创建指示器的动态宽度和位置
    const inputRange = navigationState.routes.map((_, i) => i);
    const layoutWith = scaleSize(350);
    const translateX = position.interpolate({
        inputRange,
        outputRange: inputRange.map(i => i * layoutWith / 3 + ((layoutWith / 3) - layoutWith / 13) / 2),
        // outputRange: [48, 162], // 这里的值需要根据实际情况计算
    });


    return (
        <View style={styles.tabHeader}>
            <View style={styles.tabBar}>
                {navigationState.routes.map((route, i) => (
                    <TouchableOpacity
                        key={route.key}
                        onPress={() => setIndex(i)}
                        style={styles.tabItem}>
                        <Text style={{ color: navigationState.index === i ? '#EC6138' : 'black', textAlign: "left" }}>
                            {route.title}
                        </Text>
                    </TouchableOpacity>
                ))}
                {/* 自定义指示器 */}
                <Animated.View
                    style={[
                        styles.indicator,
                        { transform: [{ translateX }] },
                        { width: scaleSize(26) } // 指示器的宽度
                    ]}
                />
            </View>
        </View>
    );
};




export default function moneyScreen() {

    const router = useRouter();
    const layout = useWindowDimensions();


    const [index, setIndex] = React.useState(1);
    const [routes] = React.useState([
        { key: 'experience', title: '娱粮' },
        { key: 'money', title: '余额' },
        { key: 'card', title: '卡包' },
    ]);


    const renderScene = SceneMap({
        experience: experienceRoute,
        money: moneyRoute,
        card: cardRoute
    });



    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '我的钱包', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#FFF', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                    headerRight: () => {
                        if (index == 0) {
                            return (
                                <TouchableOpacity
                                    onPress={() => {
                                        router.push("/money/rule")
                                    }}
                                    style={{ paddingRight: 15 }}
                                >
                                    <View>
                                        <Text style={{ color: "#2A2B30", fontSize: 14, }}>规则说明</Text>
                                    </View>
                                </TouchableOpacity>
                            )
                        }  else {
                            return null
                        };
                    }
                }}
            />
            <TabView
                navigationState={{ index, routes }}
                renderScene={renderScene}
                onIndexChange={setIndex}
                initialLayout={{ width: layout.width }}
                renderTabBar={(props) => <CustomTabBar {...props} setIndex={setIndex} />} // 使用自定义的 TabBar
            />
        </View>

    );
}

const styles = StyleSheet.create({
    scene: {
        flex: 1,
        // justifyContent: 'center',
        // alignItems: 'center',
    },
    tabBar: {
        flexDirection: 'row',
        backgroundColor: 'white',
        position: 'relative', // 需要相对定位来放置指示器
        width:scaleSize(350),
        margin: "auto",
    },
    tabItem: {
        flex: 1,
        alignItems: 'center',
        paddingTop: 10,
        paddingBottom: 9,
        fontSize: 14,
        color: "#2A2B30",
    },
    indicator: {
        position: 'absolute',
        height: 3,
        backgroundColor: '#EC6138',
        bottom: 0,
        borderRadius: 5,
    },
    tabHeader: {
        backgroundColor: "#fff",
        borderBottomWidth: 1,
        borderBottomColor: "#F1F2F5"
    },
    experienceContainer: {
        marginLeft: 12,
        marginRight: 12,
        marginTop: 12,
        margin: "auto"
    },
    experienceHeaderCard: {
        paddingTop: 14,
    },
    moneyCard: {
        margin: "auto",
    },
    moneyCardText: {
        fontSize: 26,
        color: "#EC6138"
    },
    exchangeBtn: {
        width: scaleSize(66),
        height: scaleSize(27),
        borderRadius: 13,
        borderStyle: "solid",
        borderWidth: 0.5,
        borderColor: "#EC6138",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        margin: "auto",
        marginTop: 10,
        marginBottom: 12,
    },
    exchangeBtnText: {
        color: "#EC6138",
        fontSize: 12,
    },
    experienceListContainer: {
        marginTop: 12,
        borderRadius: 10,
        paddingLeft: 12,
        paddingRight: 12,
        backgroundColor: "#fff"
    },
    experienceContent: {
        // margin: 12,
        backgroundColor: "#fff",
        // marginLeft: 10,
        // paddingRight: 10,

        paddingBottom: 17,
        paddingTop: 17,
        borderBottomColor: "#E4E6EC",
        borderBottomWidth: 0.5,
    },
    experienceTitleWrap: {
        flexDirection: "row",
        justifyContent: "space-between",
    },
    experienceDate: {
        marginTop: 6,
    },
    experienceTitles: {
        fontSize: 14,
        color: "#2A2B30",
    },
    experienceNumber: {
        fontSize: 14,
        color: "#EC6138",
    },
    experienceDateText: {
        fontSize: 14,
        color: "#676978",
    },
    noBottom: {
        borderBottomWidth: 0,
    },
    moneyContainer: {
        margin: 12,
    },
    moneyYueCard: {
        borderRadius: 10,
        overflow: "hidden",

    },
    moneyYueMoneyWarp: {
        paddingTop: 20,
        paddingBottom: 14,
        borderBottomWidth: 0.5,
        borderColor: "#fff",
        marginLeft: 12,
        marginRight: 12,
    },
    moneyYueMoneyWarpTitle: {
        margin: "auto",
    },
    moneyYueMoneyWarpTitleText: {
        fontSize:12,
        color: "#fff",
    },
    moneyYueMoneyWarpTitleNumber: {
        margin: "auto",
        marginTop: 1,
    },
    moneyYueMoneyWarpTitleNumberText: {
        fontSize:26,
        color: "#fff",
    },
    submitWarp: {
        flexDirection: "row",
        marginTop: 18,
        marginBottom: 16,
        justifyContent: "space-around",
        paddingLeft: 40,
        paddingRight: 40,
    },
    reqMoney: {
        width: 130,
        height: 32,
        borderRadius: 20,
        borderWidth: 1,
        borderColor: "#fff",
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    reqMoneyText: {
        color: "#fff"
    },
    reqMoneyHistory: {
        width: 130,
        height: 32,
        borderRadius: 20,
        borderWidth: 1,
        borderColor: "#fff",
        flexDirection: "row",
        backgroundColor: "#fff",
        justifyContent: "center",
        alignItems: "center",
    },
    reqMoneyHistoryText: {
        color: "#EC6138",
    },
    billContainer: {
        backgroundColor: "#fff",
        borderRadius: 10,
        marginTop: 12,
        paddingLeft: 12,
        paddingRight: 12,
    },
    billList: {
        paddingTop: 17,
        paddingBottom: 17,
        flexDirection: 'row',
        justifyContent: "space-between",
        borderWidth: 0.5,
        borderColor: "#F7F7F7"
    },
    billMoney: {
        color: "#EC6138"
    },
    toolWrap: {
        width: scaleSize(220),
        height: scaleSize(220),
        margin: "auto",
        // backgroundColor: "red",
        marginTop: 57,
    },
    empty_wrap: {
        marginTop: 185,
    },
    empty_text: {
        fontSize: 14,
        textAlign: "center",
        color: "#9C9EAC",
        paddingLeft: 10,
    },
});
